package org.lep.leetcode.pascaltriangle;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Source : https://oj.leetcode.com/problems/pascals-triangle/
 *
 * Created by lverpeng on 2017/8/18.
 *
 * Given numRows, generate the first numRows of Pascal's triangle.
 *
 * For example, given numRows = 5,
 * Return
 *
 * [
 *      [1],
 *     [1,1],
 *    [1,2,1],
 *   [1,3,3,1],
 *  [1,4,6,4,1]
 * ]
 *
 *
 */
public class PascalTiangle {

    /**
     * 生成杨辉三角（帕斯卡三角形）
     *
     * @param n
     * @return
     */
    public List<List<Integer>> generate (int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>(n);
        if (n == 0) {
            return result;
        }
        result.add(Arrays.asList(new Integer[]{1}));
        for (int i = 2; i <= n; i++) {
            List<Integer> list = new ArrayList<Integer>(i);
            list.add(1);
            for (int j = 1; j < i-1; j++) {
                list.add(result.get(i-2).get(j-1) + result.get(i-2).get(j));
            }
            list.add(1);
            result.add(list);
        }
        return result;
    }

    public void print (List<List<Integer>> list) {
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j <= list.size() - i; j++) {
                System.out.print(" ");
            }
            System.out.println(Arrays.toString(list.get(i).toArray(new Integer[list.get(i).size()])));
        }
    }

    public static void main(String[] args) {
        PascalTiangle pascalTiangle = new PascalTiangle();
        pascalTiangle.print(pascalTiangle.generate(5));
    }
}
